<template>
	<view class="profile-page">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="back-btn" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			<text class="header-title">基本资料</text>
			<view class="edit-btn" @click="enableEdit">
				<text class="edit-text">{{ isEditing ? '保存' : '编辑' }}</text>
			</view>
		</view>
		

		<!-- 头像和基本信息 -->
		<view class="avatar-section">
			<view class="avatar-wrapper" @click="chooseAvatar">
				<image class="avatar" :src="profile.avatar || defaultAvatar" mode="aspectFill"></image>
				<view class="avatar-badge" v-if="profile.isVip">
					<text class="vip-icon">👑</text>
				</view>
				<view class="avatar-edit-hint">
					<text class="edit-hint-icon">📷</text>
				</view>
			</view>
			<text class="nickname">{{ profile.realName || profile.nickname || '未设置' }}</text>
			<text class="user-id">ID: {{ profile.userId || '未知' }}</text>
		</view>
		
		<!-- 编辑提示 -->
		<view class="edit-tip" v-if="!isEditing">
			<text class="tip-text">💡 点击任意字段即可编辑</text>
		</view>

		<scroll-view scroll-y class="content-scroll">
			<!-- 个人信息 -->
			<view class="section">
				<view class="section-title">个人信息</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">真实姓名</text>
					<input v-if="isEditing" class="input" v-model="profile.realName" placeholder="请输入真实姓名" />
					<text v-else class="value">{{ profile.realName || '未设置' }}</text>
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">身份证号</text>
					<input v-if="isEditing" class="input" v-model="profile.idCard" placeholder="请输入身份证号" />
					<text v-else class="value">{{ formatIdCard(profile.idCard) }}</text>
					<text class="verify-status verified" v-if="profile.idCard && profile.isRealNameVerified">✓已认证</text>
					<text class="verify-status unverified" v-else-if="!profile.idCard">未认证</text>
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">性别</text>
					<picker v-if="isEditing" :range="genderOptions" range-key="label" :value="getGenderIndex()" @change="onGenderChange">
						<view class="picker-value">{{ getGenderText() }}</view>
					</picker>
					<text v-else class="value">{{ getGenderText() }}</text>
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">出生日期</text>
					<picker v-if="isEditing" mode="date" :value="profile.birthDate" @change="onBirthDateChange">
						<view class="picker-value">{{ profile.birthDate || '请选择' }}</view>
					</picker>
					<text v-else class="value">{{ profile.birthDate || '未设置' }}</text>
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">身高</text>
					<input v-if="isEditing" class="input" type="number" v-model="profile.height" placeholder="请输入身高（cm）" />
					<text v-else class="value">{{ profile.height ? profile.height + ' cm' : '未设置' }}</text>
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">体重</text>
					<input v-if="isEditing" class="input" type="number" v-model="profile.weight" placeholder="请输入体重（kg）" />
					<text v-else class="value">{{ profile.weight ? profile.weight + ' kg' : '未设置' }}</text>
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">星座</text>
					<picker v-if="isEditing" :range="starOptions" @change="onStarChange">
						<view class="picker-value">{{ profile.star || '请选择' }}</view>
					</picker>
					<text v-else class="value">{{ profile.star || '未设置' }}</text>
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">生肖</text>
					<picker v-if="isEditing" :range="animalOptions" @change="onAnimalChange">
						<view class="picker-value">{{ profile.animal || '请选择' }}</view>
					</picker>
					<text v-else class="value">{{ profile.animal || '未设置' }}</text>
				</view>
			</view>

			<!-- 学业与工作 -->
			<view class="section">
				<view class="section-title">学业与工作</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">学历</text>
					<picker v-if="isEditing" :range="educationOptions" :value="getEducationIndex()" @change="onEducationChange">
						<view class="picker-value">{{ getEducationText() }}</view>
					</picker>
					<text v-else class="value">{{ getEducationText() }}</text>
					<text class="verify-status verified" v-if="profile.educationLevel && profile.isEducationVerified">✓已认证</text>
					<text class="verify-status unverified" v-else-if="!profile.educationLevel">未认证</text>
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">学校名称</text>
					<input v-if="isEditing" class="input" v-model="profile.schoolName" placeholder="请输入学校名称" />
					<text v-else class="value">{{ profile.schoolName || '未设置' }}</text>
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">工作单位</text>
					<input v-if="isEditing" class="input" v-model="profile.company" placeholder="请输入工作单位" />
					<text v-else class="value">{{ profile.company || '未设置' }}</text>
					<text class="verify-status verified" v-if="profile.company && profile.isWorkVerified">✓已认证</text>
					<text class="verify-status unverified" v-else-if="!profile.company">未认证</text>
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">职位</text>
					<input v-if="isEditing" class="input" v-model="profile.jobTitle" placeholder="请输入职位" />
					<text v-else class="value">{{ profile.jobTitle || '未设置' }}</text>
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">薪资范围</text>
					<picker v-if="isEditing" :range="salaryOptions" :value="getSalaryIndex()" @change="onSalaryChange">
						<view class="picker-value">{{ getSalaryText() }}</view>
					</picker>
					<text v-else class="value">{{ getSalaryText() }}</text>
				</view>
			</view>

			<!-- 婚姻与住房 -->
			<view class="section">
				<view class="section-title">婚姻与住房</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">婚姻状况</text>
					<picker v-if="isEditing" :range="maritalOptions" :value="getMaritalIndex()" @change="onMaritalChange">
						<view class="picker-value">{{ getMaritalText() }}</view>
					</picker>
					<text v-else class="value">{{ getMaritalText() }}</text>
					<text class="verify-status verified" v-if="profile.maritalStatus !== null && profile.maritalStatus !== undefined && profile.isMaritalVerified">✓已认证</text>
					<text class="verify-status unverified" v-else-if="profile.maritalStatus === null || profile.maritalStatus === undefined">未认证</text>
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">房产</text>
					<picker v-if="isEditing" :range="houseOptions" range-key="label" :value="getHouseIndex()" @change="onHouseChange">
						<view class="picker-value">{{ getHouseText() }}</view>
					</picker>
					<text v-else class="value">{{ getHouseText() }}</text>
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">车辆</text>
					<picker v-if="isEditing" :range="carOptions" range-key="label" :value="getCarIndex()" @change="onCarChange">
						<view class="picker-value">{{ getCarText() }}</view>
					</picker>
					<text v-else class="value">{{ getCarText() }}</text>
				</view>
			</view>

			<!-- 兴趣爱好 -->
			<view class="section">
				<view class="section-title">兴趣爱好</view>
				
				<view class="info-item column" @click="startEdit">
					<text class="label">兴趣爱好标签</text>
					<view class="hobby-tags">
						<view class="hobby-tag" 
							v-for="(hobby, index) in hobbyList" 
							:key="index"
							@click.stop="isEditing ? removeHobbyTag(index) : null"
							:class="{ deletable: isEditing }"
						>
							{{ hobby }}
							<text class="delete-icon" v-if="isEditing">×</text>
						</view>
						<view class="hobby-tag add" v-if="isEditing" @click.stop="addHobby">
							+ 添加
						</view>
						<view class="hobby-empty" v-if="hobbyList.length === 0 && !isEditing">
							<text class="empty-text">暂无标签</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 隐私设置 -->
			<view class="section">
				<view class="section-title">隐私设置</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">薪资公开</text>
					<switch :checked="profile.privacySalary === 1" @change="onPrivacySalaryChange" :disabled="!isEditing" />
				</view>
				
				<view class="info-item" :class="{ editing: isEditing }" @click="startEdit">
					<text class="label">手机号公开</text>
					<switch :checked="profile.privacyPhone === 1" @change="onPrivacyPhoneChange" :disabled="!isEditing" />
				</view>
			</view>

			<!-- 真实度评分 -->
			<view class="section">
				<view class="section-title">真实度评分</view>
				
				<view class="authenticity-score">
					<view class="score-circle">
						<text class="score-number">{{ profile.authenticityScore || 0 }}</text>
						<text class="score-total">/100</text>
					</view>
					<view class="score-tips">
						<text class="tip-text">完善资料并通过认证可提升真实度评分</text>
					</view>
				</view>
			</view>
			
			<!-- 底部占位 -->
			<view class="bottom-placeholder"></view>
		</scroll-view>
		
		<!-- 标签选择弹窗 -->
		<view class="hobby-modal" v-if="showHobbyModal" @click="closeHobbyModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">选择兴趣爱好标签</text>
					<text class="close-btn" @click="closeHobbyModal">×</text>
				</view>
				
				<scroll-view scroll-y class="modal-body">
					<!-- 预设标签分类 -->
					<view class="hobby-category" v-for="(category, index) in hobbyCategories" :key="index">
						<view class="category-title">
							<text class="category-icon">{{ category.icon }}</text>
							<text class="category-name">{{ category.name }}</text>
						</view>
						<view class="category-tags">
							<view class="preset-tag" 
								v-for="(tag, tagIndex) in category.tags" 
								:key="tagIndex"
								@click="selectPresetTag(tag)"
								:class="{ selected: hobbyList.includes(tag) }"
							>
								{{ tag }}
								<text class="check-icon" v-if="hobbyList.includes(tag)">✓</text>
							</view>
						</view>
					</view>
					
					<!-- 自定义输入 -->
					<view class="custom-input-section">
						<view class="category-title">
							<text class="category-icon">✏️</text>
							<text class="category-name">自定义标签</text>
						</view>
						<view class="input-wrapper">
							<input 
								class="custom-input" 
								v-model="customHobbyInput" 
								placeholder="输入自定义标签"
								@confirm="addCustomTag"
							/>
							<view class="add-custom-btn" @click="addCustomTag">
								<text class="add-text">添加</text>
							</view>
						</view>
					</view>
				</scroll-view>
				
				<view class="modal-footer">
					<text class="selected-count">已选择 {{ hobbyList.length }}/10 个标签</text>
					<view class="done-btn" @click="closeHobbyModal">
						<text class="done-text">完成</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import userAuth from '@/utils/userAuth.js'
	
	export default {
		data() {
			return {
				gatewayURL: 'http://localhost:8083',
				currentUserId: null,
				isEditing: false,
				defaultAvatar: 'https://via.placeholder.com/150',
				
				// 用户资料数据
				profile: {
					userId: null,
					avatar: '',
					nickname: '',
					realName: '',
					idCard: '',
					gender: null,
					birthDate: '',
					height: null,
					weight: null,
					star: '',
					animal: '',
					educationLevel: null,
					schoolName: '',
					company: '',
					jobTitle: '',
					salaryRange: null,
					maritalStatus: null,
					house: null,
					car: null,
					hobby: '',
					privacySalary: 0,
					privacyPhone: 0,
					authenticityScore: 0,
					isVip: false,
					isRealNameVerified: false,
					isEducationVerified: false,
					isWorkVerified: false,
					isMaritalVerified: false
				},
				
				// 选项列表
				genderOptions: [
					{ value: 1, label: '男' },
					{ value: 2, label: '女' }
				],
				starOptions: ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', 
				             '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座'],
				animalOptions: ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'],
				educationOptions: ['高中', '专科', '本科', '硕士', '博士', '无'],
				salaryOptions: ['1-5k', '5-10k', '10-20k', '20-50k', '50k+'],
				maritalOptions: ['未婚', '离异', '丧偶'],
				houseOptions: [
					{ value: 0, label: '无' },
					{ value: 1, label: '有' }
				],
				carOptions: [
					{ value: 0, label: '无' },
					{ value: 1, label: '有' }
				],
				
				// 标签选择弹窗
				showHobbyModal: false,
				hobbyCategories: [
					{
						name: '运动健身',
						icon: '🏃',
						tags: ['运动', '健身', '瑜伽', '爬山', '游泳', '篮球', '足球', '网球']
					},
					{
						name: '文艺休闲',
						icon: '🎨',
						tags: ['旅游', '阅读', '音乐', '电影', '摄影', '绘画', '舞蹈', '唱歌']
					},
					{
						name: '技能爱好',
						icon: '🎹',
						tags: ['钢琴', '吉他', '书法', '茶艺', '烹饪', '园艺', '手工', '收藏']
					},
					{
						name: '生活方式',
						icon: '🌟',
						tags: ['美食', '游戏', '宠物', '时尚', '购物', '化妆']
					}
				],
				customHobbyInput: ''
			}
		},
		computed: {
			hobbyList() {
				if (!this.profile.hobby) return []
				try {
					return JSON.parse(this.profile.hobby)
				} catch (e) {
					return this.profile.hobby.split(',').filter(item => item)
				}
			}
		},
	onLoad() {
		// 获取登录用户ID - 使用userAuth工具类
		this.currentUserId = userAuth.getUserId()
		
		console.log('=== 个人资料页面 ===')
		console.log('用户ID:', this.currentUserId)
		console.log('用户ID类型:', typeof this.currentUserId)
		
		// 检查是否已登录（userId为1也是合法的测试用户）
		if (this.currentUserId === null || this.currentUserId === undefined || this.currentUserId === 0) {
			console.log('未登录，检查登录状态')
			this.checkLoginStatus()
		} else {
			console.log('已登录，用户ID:', this.currentUserId)
			// 加载用户资料
			this.loadProfile()
		}
	},
		methods: {
			// 选择并上传头像
			chooseAvatar() {
				uni.showActionSheet({
					itemList: ['从相册选择', '拍照'],
					success: (res) => {
						if (res.tapIndex === 0) {
							// 从相册选择
							this.selectImage('album')
						} else if (res.tapIndex === 1) {
							// 拍照
							this.selectImage('camera')
						}
					}
				})
			},
			
			// 选择图片
			selectImage(sourceType) {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'], // 使用压缩图
					sourceType: [sourceType],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]
						console.log('选择的图片路径:', tempFilePath)
						// 上传图片
						this.uploadAvatar(tempFilePath)
					},
					fail: (err) => {
						console.error('选择图片失败:', err)
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						})
					}
				})
			},
			
			// 上传头像
			uploadAvatar(filePath) {
				console.log('=== 开始上传头像 ===')
				console.log('文件路径:', filePath)
				console.log('上传URL:', this.gatewayURL + '/api/avatar/upload')
				console.log('用户ID:', this.currentUserId)
				
				uni.showLoading({
					title: '上传中...',
					mask: true
				})
				
				// 使用 uni.uploadFile 上传到服务器
				const uploadTask = uni.uploadFile({
					url: this.gatewayURL + '/api/avatar/upload',
					filePath: filePath,
					name: 'file',
					timeout: 60000, // 设置超时时间为60秒
					formData: {
						userId: this.currentUserId
					},
					success: (uploadRes) => {
						uni.hideLoading()
						console.log('上传响应:', uploadRes)
						console.log('状态码:', uploadRes.statusCode)
						
						// 检查HTTP状态码
						if (uploadRes.statusCode !== 200) {
							console.error('HTTP错误:', uploadRes.statusCode)
							uni.showToast({
								title: `服务器错误: ${uploadRes.statusCode}`,
								icon: 'none',
								duration: 3000
							})
							return
						}
						
						try {
							const result = JSON.parse(uploadRes.data)
							console.log('解析后的结果:', result)
							
							if (result.code === 200) {
								console.log('✅ 头像上传成功:', result.data)
								
								// 更新头像URL
								this.profile.avatar = result.data
								
								// 更新本地存储的用户信息
								const userInfo = uni.getStorageSync('userInfo')
								if (userInfo) {
									userInfo.avatarUrl = result.data
									uni.setStorageSync('userInfo', userInfo)
									console.log('已更新本地缓存')
								}
								
								uni.showToast({
									title: '头像上传成功',
									icon: 'success',
									duration: 2000
								})
								
								// 刷新页面数据
								setTimeout(() => {
									this.loadProfile()
								}, 500)
							} else {
								console.error('❌ 业务错误:', result.message)
								uni.showToast({
									title: result.message || '上传失败',
									icon: 'none',
									duration: 3000
								})
							}
						} catch (e) {
							console.error('❌ 解析响应失败:', e)
							console.error('原始响应数据:', uploadRes.data)
							uni.showToast({
								title: '服务器响应格式错误',
								icon: 'none',
								duration: 3000
							})
						}
					},
					fail: (err) => {
						uni.hideLoading()
						console.error('❌ 上传失败:', err)
						
						let errorMsg = '上传失败'
						if (err.errMsg) {
							if (err.errMsg.includes('timeout')) {
								errorMsg = '上传超时，请检查网络连接'
							} else if (err.errMsg.includes('fail')) {
								errorMsg = '网络连接失败'
							} else {
								errorMsg = err.errMsg
							}
						}
						
						uni.showToast({
							title: errorMsg,
							icon: 'none',
							duration: 3000
						})
					}
				})
				
				// 监听上传进度
				uploadTask.onProgressUpdate((res) => {
					console.log('上传进度:', res.progress + '%')
					if (res.progress % 20 === 0 || res.progress > 90) {
						console.log(`已上传 ${res.totalBytesSent}/${res.totalBytesExpectedToSend} 字节`)
					}
				})
			},
			
			// 检查登录状态
			checkLoginStatus() {
				const token = uni.getStorageSync('token')
				const userInfo = uni.getStorageSync('userInfo')
				
				if (!token || !userInfo) {
					// 没有登录信息，跳转到登录页
					uni.showModal({
						title: '需要登录',
						content: '请先登录后查看个人资料',
						showCancel: false,
						confirmText: '去登录',
						success: () => {
							uni.navigateTo({
								url: '/pages/page3/page3?redirect=' + encodeURIComponent('/pages/profile/index')
							})
						}
					})
					return false
				}
				
			if (this.currentUserId === null || this.currentUserId === undefined || this.currentUserId === 0) {
				// 有登录信息但无法获取用户ID - 登录信息异常
				uni.showModal({
					title: '登录信息异常',
					content: '登录信息不完整，请重新登录',
					showCancel: false,
					confirmText: '重新登录',
					success: () => {
						// 清除异常的登录信息
						uni.clearStorageSync()
						uni.navigateTo({
							url: '/pages/page3/page3?redirect=' + encodeURIComponent('/pages/profile/index')
						})
					}
				})
				return false
			}
				
				return true
			},
			// 加载用户资料
			loadProfile() {
				uni.showLoading({
					title: '加载中...'
				})
				
				uni.request({
					url: this.gatewayURL + '/api/user/profile?userId=' + this.currentUserId,
					method: 'GET',
					success: (res) => {
						uni.hideLoading()
						console.log('=== 用户资料加载 ===')
						console.log('完整响应:', res.data)
						
						if (res.data && res.data.code === 200) {
							console.log('原始salaryRange:', res.data.data.salaryRange)
							this.profile = { ...this.profile, ...res.data.data }
							console.log('合并后的profile.salaryRange:', this.profile.salaryRange)
							console.log('显示的薪资文本:', this.getSalaryText())
						} else {
							uni.showToast({
								title: res.data?.message || '加载失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						uni.hideLoading()
						console.error('加载用户资料失败:', err)
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
					}
				})
			},
			
			// 格式化身份证号（隐藏中间部分）
			formatIdCard(idCard) {
				if (!idCard) return '未设置'
				if (idCard.length < 8) return idCard
				return idCard.substring(0, 6) + '********' + idCard.substring(idCard.length - 4)
			},
			
			// 获取性别文本
			getGenderText() {
				const option = this.genderOptions.find(item => item.value === this.profile.gender)
				return option ? option.label : '未设置'
			},
			
			// 获取学历文本
			getEducationText() {
				if (this.profile.educationLevel === null || this.profile.educationLevel === undefined) return '未设置'
				const index = this.profile.educationLevel - 1
				return this.educationOptions[index] || '未设置'
			},
			
			// 获取薪资文本
			getSalaryText() {
				if (this.profile.salaryRange === null || this.profile.salaryRange === undefined) return '未设置'
				const index = this.profile.salaryRange - 1
				return this.salaryOptions[index] || '未设置'
			},
			
			// 获取薪资选择器的索引
			getSalaryIndex() {
				if (this.profile.salaryRange === null || this.profile.salaryRange === undefined) {
					return 0  // 默认选择第一项
				}
				const index = this.profile.salaryRange - 1
				// 确保索引在有效范围内
				return Math.max(0, Math.min(index, this.salaryOptions.length - 1))
			},
			
			// 获取性别选择器的索引
			getGenderIndex() {
				const option = this.genderOptions.findIndex(item => item.value === this.profile.gender)
				return Math.max(0, option)
			},
			
			// 获取学历选择器的索引
			getEducationIndex() {
				if (this.profile.educationLevel === null || this.profile.educationLevel === undefined) {
					return 0
				}
				const index = this.profile.educationLevel - 1
				return Math.max(0, Math.min(index, this.educationOptions.length - 1))
			},
			
			// 获取婚姻状况选择器的索引
			getMaritalIndex() {
				if (this.profile.maritalStatus === null || this.profile.maritalStatus === undefined) {
					return 0
				}
				return Math.max(0, Math.min(this.profile.maritalStatus, this.maritalOptions.length - 1))
			},
			
			// 获取房产选择器的索引
			getHouseIndex() {
				const option = this.houseOptions.findIndex(item => item.value === this.profile.house)
				return Math.max(0, option)
			},
			
			// 获取车辆选择器的索引
			getCarIndex() {
				const option = this.carOptions.findIndex(item => item.value === this.profile.car)
				return Math.max(0, option)
			},
			
			// 获取婚姻状况文本
			getMaritalText() {
				if (this.profile.maritalStatus === null || this.profile.maritalStatus === undefined) return '未设置'
				const index = this.profile.maritalStatus
				return this.maritalOptions[index] || '未设置'
			},
			
			// 获取房产文本
			getHouseText() {
				const option = this.houseOptions.find(item => item.value === this.profile.house)     
				return option ? option.label : '未设置'
			},
			
			// 获取车辆文本
			getCarText() {
				const option = this.carOptions.find(item => item.value === this.profile.car)
				return option ? option.label : '未设置'
			},
			
			// 选择器改变事件
			onGenderChange(e) {
				this.profile.gender = this.genderOptions[parseInt(e.detail.value)].value
			},
			onBirthDateChange(e) {
				this.profile.birthDate = e.detail.value
			},
			onStarChange(e) {
				this.profile.star = this.starOptions[parseInt(e.detail.value)]
			},
			onAnimalChange(e) {
				this.profile.animal = this.animalOptions[parseInt(e.detail.value)]
			},
			onEducationChange(e) {
				// 将字符串转换为数字
				this.profile.educationLevel = parseInt(e.detail.value) + 1
			},
			onSalaryChange(e) {
				console.log('=== 薪资选择变化 ===')
				console.log('选择的索引:', e.detail.value, typeof e.detail.value)
				console.log('对应的薪资选项:', this.salaryOptions[e.detail.value])
				
				// 将字符串转换为数字，避免字符串拼接问题
				this.profile.salaryRange = parseInt(e.detail.value) + 1
				
				console.log('更新后的salaryRange:', this.profile.salaryRange, typeof this.profile.salaryRange)
				console.log('更新后显示的文本:', this.getSalaryText())
			},
			onMaritalChange(e) {
				// 将字符串转换为数字
				this.profile.maritalStatus = parseInt(e.detail.value)
			},
			onHouseChange(e) {
				this.profile.house = this.houseOptions[parseInt(e.detail.value)].value
			},
			onCarChange(e) {
				this.profile.car = this.carOptions[parseInt(e.detail.value)].value
			},
			onPrivacySalaryChange(e) {
				this.profile.privacySalary = e.detail.value ? 1 : 0
			},
			onPrivacyPhoneChange(e) {
				this.profile.privacyPhone = e.detail.value ? 1 : 0
			},
			
			// 显示标签选择弹窗
			addHobby() {
				this.showHobbyModal = true
			},
			
			// 关闭标签选择弹窗
			closeHobbyModal() {
				this.showHobbyModal = false
				this.customHobbyInput = ''
			},
			
			// 选择预设标签
			selectPresetTag(tag) {
				if (this.hobbyList.includes(tag)) {
					// 如果已选中，则移除
					this.removeHobbyTag(this.hobbyList.indexOf(tag))
				} else {
					// 如果未选中，则添加
					this.addHobbyTag(tag)
				}
			},
			
			// 添加自定义标签
			addCustomTag() {
				const customTag = this.customHobbyInput.trim()
				if (customTag) {
					this.addHobbyTag(customTag)
					this.customHobbyInput = ''
				} else {
					uni.showToast({
						title: '请输入标签内容',
						icon: 'none'
					})
				}
			},
			
			// 添加标签到列表
			addHobbyTag(hobbyText) {
				let currentHobbies = this.hobbyList.slice()
				
				// 检查是否已存在
				if (currentHobbies.includes(hobbyText)) {
					uni.showToast({
						title: '标签已存在',
						icon: 'none'
					})
					return
				}
				
				// 限制标签数量
				if (currentHobbies.length >= 10) {
					uni.showToast({
						title: '最多只能添加10个标签',
						icon: 'none'
					})
					return
				}
				
				// 添加新标签
				currentHobbies.push(hobbyText)
				
				// 更新hobby字段（转为JSON格式）
				this.profile.hobby = JSON.stringify(currentHobbies)
				
				uni.showToast({
					title: '标签添加成功',
					icon: 'success'
				})
			},
			
			// 移除标签
			removeHobbyTag(index) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个标签吗？',
					success: (res) => {
						if (res.confirm) {
							let currentHobbies = this.hobbyList.slice()
							currentHobbies.splice(index, 1)
							
							// 更新hobby字段
							this.profile.hobby = currentHobbies.length > 0 ? JSON.stringify(currentHobbies) : ''
							
							uni.showToast({
								title: '标签删除成功',
								icon: 'success'
							})
						}
					}
				})
			},
			
			// 点击字段进入编辑模式
			startEdit() {
				if (!this.isEditing) {
					this.isEditing = true
					// 提示用户已进入编辑模式
					uni.showToast({
						title: '已进入编辑模式',
						icon: 'none',
						duration: 1000
					})
				}
			},
			
			// 启用编辑/保存
			enableEdit() {
				if (this.isEditing) {
					// 保存
					this.saveProfile()
				} else {
					// 进入编辑模式
					this.isEditing = true
				}
			},
			
			// 保存资料
			saveProfile(needGoBack = false) {
				uni.showLoading({
					title: '保存中...'
				})
				
				// 准备提交的数据（只包含扩展信息字段）
				const submitData = {
					userId: this.currentUserId,
					realName: this.profile.realName,
					idCard: this.profile.idCard,
					height: this.profile.height,
					weight: this.profile.weight,
					star: this.profile.star,
					animal: this.profile.animal,
					educationLevel: this.profile.educationLevel,
					schoolName: this.profile.schoolName,
					company: this.profile.company,
					jobTitle: this.profile.jobTitle,
					salaryRange: this.profile.salaryRange,
					maritalStatus: this.profile.maritalStatus,
					house: this.profile.house,
					car: this.profile.car,
					hobby: this.profile.hobby,
					privacySalary: this.profile.privacySalary,
					privacyPhone: this.profile.privacyPhone
				}
				
				uni.request({
					url: this.gatewayURL + '/api/user/profile',
					method: 'PUT',
					data: submitData,
					success: (res) => {
						uni.hideLoading()
						
						if (res.data && res.data.code === 200) {
							uni.showToast({
								title: '保存成功',
								icon: 'success',
								duration: 1500
							})
							this.isEditing = false
							// 重新加载资料
							this.loadProfile()
							
							// 如果需要返回，延迟执行返回操作
							if (needGoBack) {
								setTimeout(() => {
									this.performGoBack()
								}, 1000)
							}
						} else {
							uni.showToast({
								title: res.data?.message || '保存失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						uni.hideLoading()
						console.error('保存失败:', err)
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
					}
				})
			},
			
			// 返回上一页
			goBack() {
				try {
					// 如果正在编辑，先提醒保存
					if (this.isEditing) {
						uni.showModal({
							title: '提示',
							content: '您正在编辑资料，是否保存后返回？',
							showCancel: true,
							cancelText: '直接返回',
							confirmText: '保存并返回',
							success: (res) => {
								if (res.confirm) {
									// 保存后返回
									this.saveProfile(true)
								} else {
									// 直接返回
									this.performGoBack()
								}
							}
						})
					} else {
						// 直接返回
						this.performGoBack()
					}
				} catch (error) {
					console.error('返回操作异常:', error)
					// 异常时直接跳转到我的页面
					uni.navigateTo({
						url: '/pages/mine/index'
					})
				}
			},
			
			// 执行返回操作
			performGoBack() {
				// 检查页面栈
				const pages = getCurrentPages()
				console.log('当前页面栈长度:', pages.length)
				console.log('页面栈:', pages.map(p => p.route))
				
				if (pages.length > 1) {
					// 有上一页，正常返回
					uni.navigateBack({
						delta: 1,
						success: () => {
							console.log('返回成功')
						},
						fail: (err) => {
							console.error('返回失败:', err)
							// 返回失败时，提示用户并提供选择
							uni.showModal({
								title: '返回失败',
								content: '无法返回上一页，是否跳转到我的页面？',
								showCancel: true,
								cancelText: '留在此页',
								confirmText: '去我的页面',
								success: (modalRes) => {
									if (modalRes.confirm) {
										uni.navigateTo({
											url: '/pages/mine/index'
										})
									}
								}
							})
						}
					})
				} else {
					// 没有上一页，直接跳转到我的页面
					console.log('页面栈只有一页，跳转到我的页面')
					uni.navigateTo({
						url: '/pages/mine/index'
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.profile-page {
		min-height: 100vh;
		background: linear-gradient(180deg, #FF8A9B 0%, #FFB4C0 25%, #FFF0F2 50%, #F8F8F8 100%);
		display: flex;
		flex-direction: column;
	}

	/* 顶部导航栏 */
	.header {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 25rpx 30rpx;
		padding-top: calc(25rpx + env(safe-area-inset-top));
		background: linear-gradient(135deg, #FF8A9B 0%, #FFB4C0 100%);
		box-shadow: 0 4rpx 20rpx rgba(255, 138, 155, 0.2);
		
		.back-btn {
			position: absolute;
			left: 30rpx;
			width: 70rpx;
			height: 70rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background: rgba(255, 255, 255, 0.2);
			border-radius: 50%;
			
			.back-icon {
				font-size: 44rpx;
				color: #FFFFFF;
				font-weight: bold;
			}
		}
		
		.header-title {
			font-size: 38rpx;
			font-weight: bold;
			color: #FFFFFF;
			letter-spacing: 2rpx;
		}
		
		.edit-btn {
			position: absolute;
			right: 30rpx;
			padding: 12rpx 30rpx;
			background: rgba(255, 255, 255, 0.3);
			border-radius: 35rpx;
			min-width: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.edit-text {
				font-size: 28rpx;
				color: #FFFFFF;
				font-weight: 500;
			}
		}
	}

	/* 头像区域 */
	.avatar-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 50rpx 0 40rpx;
		
		.avatar-wrapper {
			position: relative;
			margin-bottom: 25rpx;
			cursor: pointer;
			
			.avatar {
				width: 180rpx;
				height: 180rpx;
				border-radius: 90rpx;
				border: 6rpx solid #FFFFFF;
				box-shadow: 0 8rpx 30rpx rgba(255, 138, 155, 0.3);
			}
			
			.avatar-badge {
				position: absolute;
				bottom: 5rpx;
				right: 5rpx;
				width: 50rpx;
				height: 50rpx;
				background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
				border-radius: 25rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border: 4rpx solid #FFFFFF;
				box-shadow: 0 4rpx 15rpx rgba(255, 215, 0, 0.4);
				
				.vip-icon {
					font-size: 28rpx;
				}
			}
			
			.avatar-edit-hint {
				position: absolute;
				bottom: 0;
				left: 0;
				right: 0;
				height: 60rpx;
				background: rgba(0, 0, 0, 0.5);
				border-radius: 0 0 90rpx 90rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				
				.edit-hint-icon {
					font-size: 32rpx;
					color: #FFFFFF;
				}
			}
		}
		
		.nickname {
			font-size: 40rpx;
			font-weight: bold;
			color: #333333;
			margin-bottom: 12rpx;
		}
		
		.user-id {
			font-size: 26rpx;
			color: #999999;
			background: rgba(255, 255, 255, 0.8);
			padding: 8rpx 30rpx;
			border-radius: 30rpx;
		}
	}
	
	/* 编辑提示 */
	.edit-tip {
		margin: 0 30rpx;
		background: linear-gradient(135deg, #E8F5E8 0%, #D4EDDA 100%);
		border-radius: 15rpx;
		padding: 20rpx 25rpx;
		text-align: center;
		border-left: 6rpx solid #28A745;
		
		.tip-text {
			font-size: 26rpx;
			color: #28A745;
			font-weight: 500;
		}
	}

	/* 滚动内容区域 */
	.content-scroll {
		flex: 1;
		padding: 20rpx 30rpx 0 30rpx;
		box-sizing: border-box;
	}

	/* 各个section */
	.section {
		background-color: #FFFFFF;
		border-radius: 20rpx;
		padding: 30rpx 25rpx;
		margin-bottom: 25rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
		width: 100%;
		box-sizing: border-box;
		
		.section-title {
			font-size: 34rpx;
			font-weight: bold;
			color: #333333;
			margin-bottom: 30rpx;
			padding-bottom: 20rpx;
			padding-left: 30rpx;
			border-bottom: 3rpx solid #F0F0F0;
			display: flex;
			align-items: center;
			position: relative;
			
			&::before {
				content: '';
				position: absolute;
				left: 5rpx;
				width: 8rpx;
				height: 32rpx;
				background: linear-gradient(135deg, #FF8A9B 0%, #FF6B8A 100%);
				border-radius: 4rpx;
			}
		}
		
		.info-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 30rpx 0;
			padding-left: 30rpx;
			border-bottom: 1rpx solid #F5F5F5;
			min-height: 80rpx;
			position: relative;
			transition: background-color 0.2s;
			
			&:active {
				background-color: #F8F8F8;
			}
			
			&:last-child {
				border-bottom: none;
			}
			
			&.column {
				flex-direction: column;
				align-items: flex-start;
			}
			
			// 添加右侧编辑提示（只在非编辑模式显示）
			&:not(.editing)::after {
				content: '点击编辑';
				position: absolute;
				right: 30rpx;
				color: #CCCCCC;
				font-size: 22rpx;
				opacity: 0.5;
				pointer-events: none;
			}
			
			.label {
				font-size: 30rpx;
				color: #333333;
				flex-shrink: 0;
				width: 180rpx;
				font-weight: 500;
			}
			
			.value {
				flex: 1;
				text-align: right;
				font-size: 30rpx;
				color: #666666;
				padding-left: 20rpx;
			}
			
			.input {
				flex: 1;
				text-align: right;
				font-size: 30rpx;
				color: #333333;
				padding-left: 20rpx;
			}
			
			.picker-value {
				flex: 1;
				text-align: right;
				font-size: 30rpx;
				color: #666666;
				padding-left: 20rpx;
			}
			
			.verify-status {
				margin-left: 15rpx;
				font-size: 22rpx;
				flex-shrink: 0;
				
				&.verified {
					color: #4CAF50;
				}
				
				&.unverified {
					color: #999999;
				}
			}
			
			switch {
				flex-shrink: 0;
			}
		}
	}

	/* 爱好标签 */
	.hobby-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 18rpx;
		margin-top: 20rpx;
		width: 100%;
		
		.hobby-tag {
			padding: 15rpx 30rpx;
			background: linear-gradient(135deg, #FFE5EC 0%, #FFD0DC 100%);
			border-radius: 35rpx;
			font-size: 26rpx;
			color: #FF6B8A;
			font-weight: 500;
			position: relative;
			display: flex;
			align-items: center;
			transition: all 0.3s;
			
			&.add {
				border: 2rpx dashed #FF8A9B;
				background: transparent;
				color: #FF8A9B;
				justify-content: center;
			}
			
			&.deletable {
				padding-right: 50rpx;
				
				&:active {
					background: linear-gradient(135deg, #FFB8C5 0%, #FFA3B3 100%);
					transform: scale(0.95);
				}
			}
			
			.delete-icon {
				position: absolute;
				right: 15rpx;
				top: 50%;
				transform: translateY(-50%);
				width: 30rpx;
				height: 30rpx;
				background: rgba(255, 255, 255, 0.8);
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				color: #FF6B8A;
				font-weight: bold;
			}
		}
		
		.hobby-empty {
			width: 100%;
			text-align: center;
			padding: 40rpx 0;
			
			.empty-text {
				font-size: 26rpx;
				color: #999999;
			}
		}
	}

	/* 真实度评分 */
	.authenticity-score {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 40rpx 0 20rpx;
		
		.score-circle {
			width: 200rpx;
			height: 200rpx;
			border-radius: 100rpx;
			background: linear-gradient(135deg, #FF8A9B 0%, #FF6B8A 100%);
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin-bottom: 30rpx;
			box-shadow: 0 10rpx 40rpx rgba(255, 107, 138, 0.4);
			position: relative;
			
			&::before {
				content: '';
				position: absolute;
				width: 220rpx;
				height: 220rpx;
				border-radius: 110rpx;
				border: 2rpx solid rgba(255, 138, 155, 0.3);
				top: -10rpx;
				left: -10rpx;
			}
			
			.score-number {
				font-size: 68rpx;
				font-weight: bold;
				color: #FFFFFF;
				line-height: 1;
			}
			
			.score-total {
				font-size: 26rpx;
				color: rgba(255, 255, 255, 0.95);
				margin-top: 5rpx;
			}
		}
		
		.score-tips {
			background: rgba(255, 138, 155, 0.1);
			padding: 15rpx 30rpx;
			border-radius: 30rpx;
			
			.tip-text {
				font-size: 24rpx;
				color: #FF6B8A;
				text-align: center;
			}
		}
	}

	.bottom-placeholder {
		height: 80rpx;
	}

	/* 标签选择弹窗 */
	.hobby-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;
		
		.modal-content {
			width: 90%;
			max-height: 80vh;
			background: #FFFFFF;
			border-radius: 30rpx;
			overflow: hidden;
			display: flex;
			flex-direction: column;
		}
		
		.modal-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 40rpx 30rpx 20rpx;
			background: linear-gradient(135deg, #FF8A9B 0%, #FFB4C0 100%);
			
			.modal-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #FFFFFF;
			}
			
			.close-btn {
				width: 60rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 40rpx;
				color: #FFFFFF;
				background: rgba(255, 255, 255, 0.2);
				border-radius: 30rpx;
			}
		}
		
		.modal-body {
			flex: 1;
			padding: 30rpx;
			max-height: 60vh;
		}
		
		.hobby-category {
			margin-bottom: 40rpx;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.category-title {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;
				
				.category-icon {
					font-size: 36rpx;
					margin-right: 15rpx;
				}
				
				.category-name {
					font-size: 28rpx;
					font-weight: bold;
					color: #333333;
				}
			}
			
			.category-tags {
				display: flex;
				flex-wrap: wrap;
				gap: 15rpx;
				
				.preset-tag {
					padding: 12rpx 25rpx;
					background: #F5F5F5;
					border-radius: 30rpx;
					font-size: 26rpx;
					color: #666666;
					position: relative;
					transition: all 0.3s;
					
					&.selected {
						background: linear-gradient(135deg, #FF8A9B 0%, #FF6B8A 100%);
						color: #FFFFFF;
						padding-right: 45rpx;
					}
					
					&:active {
						transform: scale(0.95);
					}
					
					.check-icon {
						position: absolute;
						right: 10rpx;
						top: 50%;
						transform: translateY(-50%);
						font-size: 20rpx;
						font-weight: bold;
					}
				}
			}
		}
		
		.custom-input-section {
			margin-top: 20rpx;
			padding-top: 30rpx;
			border-top: 1rpx solid #F0F0F0;
			
			.input-wrapper {
				display: flex;
				align-items: center;
				gap: 20rpx;
				
				.custom-input {
					flex: 1;
					padding: 20rpx 25rpx;
					background: #F8F8F8;
					border-radius: 25rpx;
					font-size: 26rpx;
					border: 2rpx solid transparent;
					
					&:focus {
						border-color: #FF8A9B;
						background: #FFFFFF;
					}
				}
				
				.add-custom-btn {
					padding: 20rpx 30rpx;
					background: linear-gradient(135deg, #FF8A9B 0%, #FF6B8A 100%);
					border-radius: 25rpx;
					
					.add-text {
						font-size: 26rpx;
						color: #FFFFFF;
						font-weight: 500;
					}
				}
			}
		}
		
		.modal-footer {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 30rpx;
			background: #F8F8F8;
			
			.selected-count {
				font-size: 26rpx;
				color: #666666;
			}
			
			.done-btn {
				padding: 20rpx 40rpx;
				background: linear-gradient(135deg, #FF8A9B 0%, #FF6B8A 100%);
				border-radius: 30rpx;
				
				.done-text {
					font-size: 28rpx;
					color: #FFFFFF;
					font-weight: bold;
				}
			}
		}
	}
</style>

